import { useUserAuthApi } from '@/api/auth';
import type { IOriginMenuItem } from '@code4x/types';
import { useMenuStore } from '@code4x/layout';
import { genRoutesAndMenus } from '@/utils/menu';
import { type RouteRecordRaw } from 'vue-router';

const usePermissionStore = defineStore('permissionStore', () => {
  /**
   * 原始菜单
   */
  const originMenus = shallowRef<IOriginMenuItem[]>([]);
  /**
   * 展开的菜单
   */
  const flattedMenus = shallowRef<IOriginMenuItem[]>([]);
  const permissionMenus = ref([]) as Ref<RouteRecordRaw[]>;
  /**
   * 获取原始菜单
   */
  const getOriginMenus = async () => {
    try {
      const { data } = await useUserAuthApi.getMenus();
      originMenus.value = data;
      const { flatted, permission } = genRoutesAndMenus(data);
      flattedMenus.value = flatted;
      permissionMenus.value = permission;
      const menuStore = useMenuStore();
      menuStore.genMenuListFromOrigin(originMenus.value);
    } catch (error) {
      console.error(Error, error);
    }
    console.log('xxxxxxxxxxxxxxxxxxxxxxxx:flatted', flattedMenus.value);
    console.log('xxxxxxxxxxxxxxxxxxxxxxxx:permission', permissionMenus.value);
    return permissionMenus.value;
  };
  return {
    originMenus,
    flattedMenus,
    permissionMenus,
    getOriginMenus,
  };
});

export default usePermissionStore;
